import { Injectable } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import axios from 'axios';
import { Transform } from 'stream';

@Injectable()
export class BaiDuAiService {
    private readonly API_KEY: string;
    private readonly SECRET_KEY: string;
    private accessToken: string;

    constructor(private configService: ConfigService) {
        this.API_KEY = this.configService.get("baidu").app_id
        this.SECRET_KEY = this.configService.get("baidu").app_key
        if (!this.API_KEY || !this.SECRET_KEY) {
            throw new Error('百度AI配置未找到，请检查配置文件');
        }
        this.getAccessToken();
    }

    private async getAccessToken() {
        try {
            const response = await axios.post(
                `https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=${this.API_KEY}&client_secret=${this.SECRET_KEY}`,
            );
            this.accessToken = response.data.access_token;
            return this.accessToken;
        } catch (error) {
            throw new Error('获取百度AI access token失败：' + error.message);
        }
    }

    async callBaiduAiApi(url: string, params: any) {
        try {
            const response = await axios.post(
                `${url}?access_token=${this.accessToken}`,
                params,
                {
                    headers: {
                        'Content-Type': 'application/json',
                        Accept: 'application/json',
                    },
                },
            );
            return response.data;
        } catch (error) {
            throw new Error('调用百度AI API失败：' + error.message);
        }
    }
    // v2 版本 API 调用
    async callBaiduAiV2(messages) {
        if (!this.accessToken) {
            await this.getAccessToken();
        }
        try {
            const response = await axios.post(
                `https://qianfan.baidubce.com/v2/chat/completions`,
                {
                    messages,
                    model: 'ernie-3.5-8k',
                    stream: true
                },
                {
                    headers: {
                        'Content-Type': 'application/json',
                        Accept: 'application/json',
                        Authorization: 'Bearer bce-v3/ALTAK-0J3qRYJmB39d7W1hRYw5f/fc088dcb3c1de039bd666738fec1177774904f72'
                    },
                    responseType: 'stream'
                }
            );

            const sseTransform = new Transform({
                transform(chunk, _, callback) {
                    this.push(chunk.toString());
                    callback();
                },
                final(callback) {
                    this.push('event: end\ndata: {}\n\n');
                    callback();
                }
            });

            response.data
                .on('data', (chunk) => sseTransform.write(chunk))
                .on('end', () => sseTransform.end())
                .on('error', (error) => {
                    sseTransform.emit('error', new Error(`流式传输错误: ${error.message}`));
                });

            return sseTransform;
        } catch (error) {
            throw new Error('调用百度AI V2接口失败：' + error.message);
        }
    }
}
